package com.ep.xml;

import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;

import java.io.ByteArrayInputStream;
import java.lang.reflect.Field;

/**
 * Created by Administrator on 2017/8/7.
 */

public class XmlUtil {
    /**
     * 解析某个标签的内容，返回该标签的一个对象
     * @param xmlResult
     * @param clz
     * @param tagName
     * @param <T>
     * @return
     */
    public static <T>T xmlToObject(String xmlResult, Class<T> clz, String tagName){
        XmlPullParser parser= Xml.newPullParser();
        T t=null;
        try {
            parser.setInput(new ByteArrayInputStream(xmlResult.getBytes("UTF-8")),"UTF-8");
            int eventType=parser.getEventType();
            while (eventType!=XmlPullParser.END_DOCUMENT){
                switch (eventType){
                    case XmlPullParser.START_DOCUMENT:{
                    }break;
                    case XmlPullParser.START_TAG:{
                        if (t != null) {
                            try {
                                Field field = clz.getDeclaredField(parser.getName());
                                if (field != null) {
                                    field.setAccessible(true);
                                    String type = field.getType().getSimpleName();
                                    if (type.contains("String")) {
                                        field.set(t, parser.nextText());
                                    } else if (type.contains("int")) {
                                        field.set(t,Integer.valueOf(parser.nextText()));
                                    } else if (type.contains("boolean")) {
                                        field.set(t,Boolean.valueOf(parser.nextText()));
                                    } else if (type.contains("float")) {
                                        field.set(t,Float.valueOf(parser.nextText()));
                                    } else if (type.contains("double")) {
                                        field.set(t,Double.valueOf(parser.nextText()));
                                    }else if (type.contains("long")) {
                                        field.set(t,Long.valueOf(parser.nextText()));
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        if (tagName.equals(parser.getName())){
                            t=clz.newInstance();
                        }

                    }break;
                    case XmlPullParser.END_TAG:{

                    }break;
                }
                eventType=parser.next();
            }
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

}
